package com.netty.esc.config.websocket;

import com.netty.esc.entity.business.UserAndChannelDTO;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Author: zhaoyang
 * @Data: 2022/5/21 20:33
 * @Description Channel对应客户端机器人资源
 * 统一：建立连接时添加
 * 断开连接时移除
 */
public class ChannelGroups {


    /**
     * channel组 （Set集合）
     * 通过ChannelId可以获取到Channel
     */
    public static ChannelGroup channelsApp = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 用户id关联 ChannelId
     */
    public static ConcurrentHashMap<Long, ChannelId> robotToChannel = new ConcurrentHashMap<>();

    /**
     * robotType 对应的所有Channel
     */
//    public static ConcurrentHashMap<String, ChannelGroup> robotTypeToChannel = new ConcurrentHashMap<>();

    /**
     * ChannelId关联机器人Id
     */
    public static ConcurrentHashMap<ChannelId, Long> channelToRobot = new ConcurrentHashMap<>();

    /**
     * 机器人id绑定机器人类型
     */
//    public static ConcurrentHashMap<String, String> robotIdToType = new ConcurrentHashMap<>();

    /**
     * 根据用户id获取channel
     */
    public static Channel getChannelByUerId(Long userId){
        //获取channelID
        ChannelId channelId = ChannelGroups.robotToChannel.get(userId);
        //修复判断用户不在线时，去查询channel报空指针问题
        if (channelId == null){
            return null;
        }
        //获取channel
        return ChannelGroups.channelsApp.find(channelId);
    }

    /**
     * 根据用户id列表批量获取channel
     */
    public static List<UserAndChannelDTO> getChannelListByUserId(List<Long> userList){
        return userList.stream().filter(e->ChannelGroups.robotToChannel.get(e) != null).map(userId -> {
            ChannelId channelId = ChannelGroups.robotToChannel.get(userId);
            //获取channel
                Channel channel = ChannelGroups.channelsApp.find(channelId);
                UserAndChannelDTO userAndChannelDTO = new UserAndChannelDTO();
                userAndChannelDTO.setChannel(channel);
                userAndChannelDTO.setUserId(userId);
                return userAndChannelDTO;
        }).collect(Collectors.toList());
    }


}
